package control

import (
	"service/app/dao"
	"service/app/dto"
	"service/app/mode"
	"service/utils"
)

type RoleControl struct {
	Dao *dao.RoleDao
}

var roleControl *RoleControl

func RoleControlInit() *RoleControl {
	if roleControl == nil {
		roleControl = &RoleControl{
			Dao: dao.RoleDaoInit(),
		}
	}
	return roleControl
}

/** 获取指定角色permList*/
func (m *RoleControl) Role_permListC(roleId *dto.ReqUriIdDto) (*[]mode.Db_menu, error) {
	return m.Dao.Role_permListD(roleId)
}

func (m *RoleControl) RoleUpdataPermC(id *dto.ReqUriIdDto, permList *dto.Ipm_pmIntList) (*[]mode.Db_pm, error) {
	return m.Dao.RoleUpdataPermD(id, permList)
}

func (m *RoleControl) RolesPermC(roleList *dto.IroleUdataList) (*[]mode.Db_pm, error) {
	return m.Dao.RolesPermD(roleList)
}
func (m *RoleControl) RoleAndUsersC(opt *dto.ReqPaginat) (*[]mode.IresUserList, int64, error) {
	return m.Dao.RoleAndUsersD(opt)
}

func (m *RoleControl) RoleAddC(param *dto.RoleAdd) error {
	return m.Dao.RoleAddD(param)
}

func (m *RoleControl) RoleListC() (*[]mode.Db_roles, error) {
	return m.Dao.RoleListD()
}

func (m *RoleControl) RolesRelation_userC(id *dto.ReqUriIdDto, roles *dto.IRolesList) error {
	originList, err := m.Role_userId_getC(id.Id)
	if err != nil {
		return err
	}
	// 去重
	var acList = utils.RemoveDuplicates(roles.Roles)
	// 原表不存在的为添加,对比后,原表留下的为删除, 新表留下的为添加
	for i := 0; i < len(originList); i++ {
		item := originList[i]
		for j := 0; j < len(acList); j++ {
			citem := acList[j]
			if int(item.ID) == citem {
				// 同时删除
				originList = append(originList[:i], originList[i+1:]...)
				acList = append(acList[:j], acList[j+1:]...)
				j--
				i--
				break
			}
		}
	}
	var addRoleList []int
	for _, v := range originList {
		addRoleList = append(addRoleList, int(v.ID))
	}
	if err := m.Role_userId_delC(id.Id, addRoleList); err != nil {
		return err
	}
	if err := m.Role_userId_addC(id.Id, acList); err != nil {
		return err
	}
	return nil
}

func (m *RoleControl) Role_userId_getC(id int) ([]mode.Db_roles, error) {
	return m.Dao.RoleList_userIdD(id)
}
func (m *RoleControl) Role_userId_addC(id int, roleId []int) error {
	return m.Dao.Role_userId_addD(id, roleId)
}
func (m *RoleControl) Role_userId_delC(id int, roleId []int) error {
	return m.Dao.Role_userId_delD(id, roleId)
}
